package com.lst.tools.mybatis.service.impl;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lst.tools.basics.function.OneParamFunctionThrowException;
import com.lst.tools.mybatis.entity.BaseModel;
import com.lst.tools.mybatis.exception.ReflectIllegalAccessException;
import com.lst.tools.mybatis.mapper.ExpandBaseMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 基础业务层实现，便于扩展
 *
 * @author: Frank
 * @date: 2019/09/24 13:51
 * @version: V1.0
 */
public class BaseService<M extends ExpandBaseMapper<T>, T> extends ServiceImpl<M, T> {

    private static final Logger LOGGER = LoggerFactory.getLogger(BaseService.class);

    @Autowired
    protected ExpandBaseMapper<T> expandBaseMapper;

    private Class<T> clazz;

    public BaseService() {
        ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        clazz = (Class<T>) type.getActualTypeArguments()[1];
    }

    /**
     * 获取实体类主键
     *
     * @return
     */
    private static Field getField(String keyFieldName, Class<?> clazz) {
        Field[] fields = clazz.getDeclaredFields();
        Field item = null;
        for (Field field : fields) {
            String name = field.getName();
            TableField tableField = field.getAnnotation(TableField.class);
            if (tableField == null) {
                if (keyFieldName.equals(name)) {
                    field.setAccessible(true);
                    item = field;
                    break;
                }
            } else {
                String value = tableField.value();
                if (keyFieldName.equals(value)) {
                    field.setAccessible(true);
                    item = field;
                    break;
                }
            }
        }
        if (item == null) {
            Class<?> superclass = clazz.getSuperclass();
            if (superclass != null) {
                item = getField(keyFieldName, superclass);
            }
        }
        return item;
    }

    /**
     * 分页查询
     *
     * @param currentPage 当前页
     * @param pageSize    查询记录条数
     * @return
     */
    public IPage<T> page(long currentPage, long pageSize) {
        return this.page(currentPage, pageSize, null);
    }

    /**
     * 分页查询
     *
     * @param currentPage  当前页
     * @param pageSize     查询记录条数
     * @param queryWrapper 查询对象
     * @return
     */
    public IPage<T> page(long currentPage, long pageSize, Wrapper<T> queryWrapper) {
        Page<T> page = new Page<>(currentPage, pageSize);
        return expandBaseMapper.selectPage(page, queryWrapper);
    }

    /**
     * 条件不存在时保存
     *
     * @param t
     * @param queryWrapper
     * @return
     */
    public int saveNotExist(T t, Wrapper<T> queryWrapper) {
        if (queryWrapper == null || queryWrapper.isEmptyOfWhere()) {
            return 0;
        }
        return expandBaseMapper.insertNotExist(t, queryWrapper);
    }

    /**
     * 根据字段名和条件获取数据，并且封装已字段名的值作为key，对象为value封装成mapper
     *
     * @param keyFieldName 字段名
     * @param queryWrapper 查询对象
     * @return
     */
    public Map<Long, T> getObjectMapByLongField(String keyFieldName, Wrapper<T> queryWrapper) {
        return getObjectMapByField(keyFieldName, queryWrapper, tList -> {
            Map<Long, T> map = new HashMap<>(tList.size());
            for (T t : tList) {
                Field field = getField(keyFieldName, clazz);
                long value = (long) field.get(t);
                map.put(value, t);
            }
            return map;
        });
    }

    /**
     * 根据字段名和条件获取数据，并且封装已字段名的值作为key，对象为value封装成mapper
     *
     * @param keyFieldName 字段名
     * @param queryWrapper 查询对象
     * @return
     */
    public Map<String, T> getObjectMapByStringField(String keyFieldName, Wrapper<T> queryWrapper) {
        return getObjectMapByField(keyFieldName, queryWrapper, tList -> {
            Map<String, T> map = new HashMap<>(tList.size());
            for (T t : tList) {
                Field field = getField(keyFieldName, clazz);
                String value = (String) field.get(t);
                map.put(value, t);
            }
            return map;
        });
    }


    /**
     * 根据id集合获取数据，并且封装已字段名的值作为key，对象为value封装成mapper
     *
     * @param ids id集合
     * @return
     */
    public Map<Long, T> getMapByIds(Collection<? extends Serializable> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Collections.EMPTY_MAP;
        }
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(BaseModel.ID, ids);
        return this.getObjectMapByLongField(BaseModel.ID, queryWrapper);
    }

    /**
     * 获取数据，并且封装已字段名的值以id作为key，对象为value封装成mapper
     *
     * @return
     */
    public Map<Long, T> getAllMap() {
        return this.getObjectMapByLongField(BaseModel.ID, null);
    }


    private Map getObjectMapByField(String keyFieldName, Wrapper<T> queryWrapper, OneParamFunctionThrowException<Map, Collection<T>> fun) {
        try {
            if (StringUtils.isBlank(keyFieldName)) {
                return Collections.emptyMap();
            }
            Collection<T> tList = super.list(queryWrapper);
            if (CollectionUtils.isEmpty(tList)) {
                return Collections.emptyMap();
            }
            if (fun != null) {
                return fun.callback(tList);
            }
            return Collections.emptyMap();
        } catch (Exception e) {
            //安全权限异常，几率很小，几乎为0
            LOGGER.error("IllegalAccessException error:", e);
            throw new ReflectIllegalAccessException(e.getMessage());
        }
    }
}
